define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojox/socket',
      'noBusinessBase/heartbeat/Connection'
   ],
   function(declare, lang, socket, Connection)
   {
      return declare([Connection],
      {
         mSocket: null,
         usingSsl: false,
         constructor:function(args)
         {
            dojo.safeMixin(this, args);
         },
         postscript: function(args)
         {
            this.inherited(arguments);
      
            var wsUrl = 'ws' + (this.usingSsl ? 's' : '') + '://' + this.host + ':' + this.port;
            this.mSocket = socket({
               url: wsUrl
            });

            this.mSocket.on("message", lang.hitch(this, function(event)
            {
               var data = dojo.fromJson(event.data);
               this.onMessage(data);
            }));
            this.mSocket.on("close", lang.hitch(this, function(event)
            {
               console.log('Heartbeat closetack. :(');
               this.onClose();
            }));
            this.mSocket.on("error", lang.hitch(this, function(event)
            {
               console.log('Heartbeat errortack. :(');
               this.onClose();
            }));
            this.mSocket.on("open", function(event)
            {
               var data = event.data;
               console.log('Heartbeat pumping...');
            });
         },
         write: function(jsonStr)
         {
            this.mSocket.send(jsonStr);
            this.inherited(arguments);
         },
         close: function()
         {
            if(!this.mSocket)
               return;

            this.mSocket.close();
            this.inherited(arguments);
         }
      });
   }
);
